﻿/// <reference path="../record/record.html" />
/// <reference path="../record/record.html" />
/// <reference path="../../js/viewmodel.js" />
(function () {
    var roamingSettings = Windows.Storage.ApplicationData.current.roamingSettings;
    var roamingFolder = Windows.Storage.ApplicationData.current.roamingFolder;

    function errorHandler(e) {
        var message = new Windows.UI.Popups.MessageDialog(e.message);
        message.showAsync().done();
    }

    // play sound
    var playSound = function (invokeEvent) {
        var keyBind = invokeEvent.target.innerText.match("[^\r\n]+")[0].trim();
        var object = ViewModels.getInstanceByKeyBind(keyBind);
        WinJS.UI.executeAnimation(
            invokeEvent.target,
            {
                property: "opacity",
                delay: 0,
                duration: 167,
                timing: "linear",
                from: 0,
                to: 1
            }).then(function () {
            }, errorHandler);

        object.playSound();
    }

    // keypress event
    addEventListener("keypress", function (event) {
        var keyBind = event.char.toUpperCase();
        var object = ViewModels.getInstanceByKeyBind(keyBind);
        if (object) {
            var pressed = getElementByKeyBind(keyBind);
            WinJS.UI.executeAnimation(
            pressed,
            {
                property: "opacity",
                delay: 0,
                duration: 167,
                timing: "linear",
                from: 0,
                to: 1
            }).then(function () {
            }, errorHandler);

            object.playSound();
        }
    });

    var getElementByKeyBind = function (keyBind) {
        var listView = document.getElementsByClassName("win-container");
        for (var i = 0; i < listView.length; i++) {
            if (keyBind === listView[i].innerText.match("[^\r\n]+")[0])
                return listView[i];
        }
    };

    // show app bar
    var addTilesSwipeEvent = function () {
        var appBar = document.getElementById("appBar").winControl;
        var selected = document.getElementsByClassName("win-selected")[0];

        if (selected) {
            appBar.disabled = false;
            appBar.show();
        }
        else {
            appBar.hide();
            appBar.disabled = true;
        }
    };

    // add new sound file picker event
    var addAddNewFileEvent = function () {
        var appBar = document.getElementById("cmdAdd");
        appBar.addEventListener("click", function () {
            var openPicker = Windows.Storage.Pickers.FileOpenPicker();

            openPicker.fileTypeFilter.append(".mp3");
            openPicker.fileTypeFilter.append(".wma");
            openPicker.fileTypeFilter.append(".wav");
            openPicker.pickSingleFileAsync().then(function (file) {
                var keyBind = document.getElementsByClassName("win-selected")[0].innerText.match("[^\r\n]+")[0];
                var object = ViewModels.getInstanceByKeyBind(keyBind);
                object.soundSource = URL.createObjectURL(file);
            }, errorHandler);
        });
    }

    var addMicEvent = function () {
        var appBar = document.getElementById("cmdMic");
        appBar.addEventListener("click", function (e) {
            var selected = document.getElementsByClassName("win-selected")[0].innerText.match("[^\r\n]+")[0];
            roamingSettings.values['keyBind'] = selected;
            window.goToRecord(e);
        });
    }

    window.goToRecord = function goToRecord(e) {
        e.preventDefault();
        WinJS.Navigation.navigate("/pages/record/record.html");
    }

    var loadLastEvent = function () {
        Data.wipeSoundTiles();
        roamingFolder.getFileAsync("last.txt").then(function (file) {
            Data.loadSoundTiles(URL.createObjectURL(file));
        });
    }

    var choosePianoEvent = function () {

        var piano = document.getElementById("piano-sounds");
        piano.addEventListener("click", function () {
            Data.wipeSoundTiles();
            Data.loadSoundTiles("/audio/piano/piano.txt");
            filePathRead = "/audio/piano/piano.txt";

            WinJS.xhr({ url: filePathRead }).then(function (file) {
                roamingFolder.createFileAsync("last.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) {
                    Windows.Storage.FileIO.writeTextAsync(newFile, file.responseText);
                }, errorHandler);
            }, errorHandler);
        });
    };

    var chooseGuitarEvent = function () {

        var guitar = document.getElementById("guitar-sounds");
        guitar.addEventListener("click", function () {
            Data.wipeSoundTiles();
            Data.loadSoundTiles("/audio/guitar/guitar.txt");
            filePathRead = "/audio/guitar/guitar.txt";


            WinJS.xhr({ url: filePathRead }).then(function (file) {
                roamingFolder.createFileAsync("last.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) {
                    Windows.Storage.FileIO.writeTextAsync(newFile, file.responseText);
                }, errorHandler);
            }, errorHandler);
        });
    };

    var chooseCustomEvent = function () {

        var guitar = document.getElementById("custom-sounds");
        guitar.addEventListener("click", function () {
            Data.wipeSoundTiles();
            Data.loadSoundTiles("/audio/default.txt");
            filePathRead = "/audio/default.txt";

            WinJS.xhr({ url: filePathRead }).then(function (file) {
                roamingFolder.createFileAsync("last.txt", Windows.Storage.CreationCollisionOption.replaceExisting).then(function (newFile) {
                    Windows.Storage.FileIO.writeTextAsync(newFile, file.responseText);
                }, errorHandler);
            }, errorHandler);
        });
    };

    WinJS.Utilities.markSupportedForProcessing(playSound);
    WinJS.Utilities.markSupportedForProcessing(addTilesSwipeEvent);

    WinJS.Namespace.define("HomeCodeBehind", {
        playSound: playSound,
        addTilesSwipeEvent: addTilesSwipeEvent,
        addAddNewFileEvent: addAddNewFileEvent,
        addMicEvent: addMicEvent,
        choosePianoEvent: choosePianoEvent,
        chooseGuitarEvent: chooseGuitarEvent,
        chooseCustomEvent: chooseCustomEvent,
        loadLastEvent: loadLastEvent
    })
})();